package com.gqzdev.xblog.controller.home;


import com.gqzdev.xblog.entity.Newsuser;
import com.gqzdev.xblog.service.NewsuserService;
import com.gqzdev.xblog.util.SendMailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * (Newsuser)表控制层
 *
 * @author ganquanzhong
 * @since 2020-03-07 21:46:53
 */
@Controller
@RequestMapping("newsuser")
public class NewsuserFrontController {
    /**
     * 服务对象
     */
    @Resource
    private NewsuserService newsuserService;

    @Autowired
    private SendMailUtil sendMailUtil;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    @ResponseBody
    public Newsuser selectOne(Integer id) {
        return this.newsuserService.queryById(id);
    }

    /**
     * description: 检查用户名
     * @Author：ganquanzhong
     * @Date： 2020/3/9 14:58
     */
    @RequestMapping(value = "checkName", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkName(@RequestParam(value = "username",required = true) String username) {
        Map<String, Object> ret = new HashMap<String, Object>();
        List<Newsuser> newsusers = newsuserService.queryByName(username);
        if (newsusers.size()==0){
            ret.put("result", "ok");
        }else{
            ret.put("result","error");
            ret.put("msg","用户名已被使用");
        }
        return ret;
    }


    @RequestMapping(value = "checkMail", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkMail(@RequestParam(value = "vcode",required = true) String vcode, HttpServletRequest request) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String code = (String)request.getSession().getAttribute("code");
        //System.out.println("验证码为"+code+"__>前台"+vcode);
        if (code.equals(vcode)) {
            ret.put("result", "ok");
        }else {
            ret.put("result","error");
            ret.put("msg","验证码有误，请重试！");
        }
        return ret;
    }


    /**
     * description: 注册
     * @Author：ganquanzhong
     * @Date： 2020/3/9 14:57
     */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    public ModelAndView add(Newsuser newsuser, @RequestParam(value = "vcode",required = false) String vcode, HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        String code = (String)request.getSession().getAttribute("code");
        //System.out.println("验证码为"+code+"__>前台"+vcode);
        newsuser.setCreatetime(new Date());
        newsuser.setStatus(1);
        Newsuser user = newsuserService.insert(newsuser);
        request.getSession().removeAttribute("loginInfo");
        if (user != null) {
            request.getSession().setAttribute("RegInfo","注册成功！请登录！");
        }else {
            request.getSession().setAttribute("RegInfo","注册失败！请重试");
        }
        model.setViewName("redirect:/");
        return model;
    }

    /**
     * description: 登录
     * @Author：ganquanzhong
     * @Date： 2020/3/9 14:57
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView login(Newsuser newsuser, @RequestParam(value = "vcode",required = false) String vcode,
                              HttpServletRequest request) throws IOException, ServletException {
        ModelAndView model = new ModelAndView();
        Newsuser user = newsuserService.queryByNamePwd(newsuser);
        request.getSession().removeAttribute("RegInfo");
        if ( user !=null ){
            user.setLasttime(new Date());
            newsuserService.update(user);
            //将登录信息保存到整个会话中
            request.getSession().setAttribute("newsuser", user);
            model.addObject("newsuser",user);
            request.getSession().setAttribute("loginInfo","");
        }else{
            //System.out.println("无改用户！");
            request.getSession().setAttribute("loginInfo","登录失败：用户名或密码错误");
        }
        model.setViewName("redirect:/");
        return model;
    }

    /**
     * exit
     */
    @RequestMapping(value = "exit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> exit(HttpSession session)  {
        Map<String, Object> retMap = new HashMap<String, Object>();
        Newsuser newsuser = (Newsuser)session.getAttribute("newsuser");
        if (null != newsuser){
            session.removeAttribute("newsuser");
        }
        retMap.put("result","ok");
        return retMap;
    }

    /**
     * 发送邮件验证码
     */
    @RequestMapping(value = "sendMail",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> sendMail(@RequestParam("email") String email, HttpServletRequest request)  {
        Map<String, Object> retMap = new HashMap<String, Object>();
        //System.out.println("发送给"+email);
        String code = String.format("%04d", new Random().nextInt(9999));
        request.getSession().setAttribute("code",code);
        String content="<div>\t\n" +
                "\t<a href=\"#\" target=\"_blank\" style=\"color:red\">【ForFuture Group】<a>\n" +
                "\t<p style=\"text-indent:2em\">欢迎注册使用【ForFuture GQZDEV】平台，你的验证码为：【"+
                code + "】。请尽快完成注册！请不要告诉别人哦！！<p>\n" +
                "</br>\n" +
                "\t<a style=\"float:right;color:#388e8fcc;\">__ForFuture Group</a>\n</div>";
        try {
            sendMailUtil.send("ForFuture 注册验证码","2027776292@qq.com",email,content);
            retMap.put("result","ok");
        } catch (MessagingException e) {
            retMap.put("result","error");
            e.printStackTrace();
        }
        retMap.put("result","ok");
        return retMap;
    }

    public static void main(String[] args){
        String code = String.format("%04d", new Random().nextInt(9999));
        String content="<div>\t\n" +
                "\t<a href=\"#\" target=\"_blank\" style=\"color:red\">ForFuture Design【gqzdev】<a>\n" +
                "\t<p style=\"text-indent:2em\">欢迎注册ForFuture平台，你的验证码为：【"+
                code + "】。请尽快完成注册！<p>\n" +
                "</br>\n" +
                "\t<a style=\"float:right;color:#388e8fcc;\">__ForFuture Group</a>\n</div>";
        System.out.println(content);
    }

}